/*
 * SortedListModel.java
 *
 * Copyright 2006 Sun Microsystems, Inc. ALL RIGHTS RESERVED Use of 
 * this software is authorized pursuant to the terms of the license 
 * found at http://developers.sun.com/berkeley_license.html .
 *
 */
package client;

import java.util.*;

import javax.swing.*;

import common.User;
 
public class SortedUserListModel extends AbstractListModel {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<User> elements = new ArrayList<User>();
    private Comparator<User> comparator;
    
    public SortedUserListModel() {
        this.comparator = new UserComparator();
    }
 
    public int getSize() {
        return elements.size();
    }
 
    public Object getElementAt(int index) {
        return elements.get(index);
    }
 
    public Comparator<User> getComparator() {
        return comparator;
    }
 
    public void addElement(User u) {
    	int index = -1;
    	for(int i =0; i<getSize(); i++){
    		if(elements.get(i).getUserId() == u.getUserId()) index = i;
    	}
    	if(index != -1){
    		elements.get(index).setStatus(u.getStatus());
    		elements.get(index).setAlias(u.getAlias());
    	}
    	else
    		elements.add(u);
        Collections.sort(elements, getComparator());
        fireContentsChanged(this, 0, getSize()-1);
    }

     private class UserComparator implements Comparator<User>{

    	@Override
    	public int compare(User o1, User o2) {
    		if(o1.getStatus() != o2.getStatus()){
    			if(o1.getStatus() == User.STATUS_OFFLINE) return 1;
    			else if(o2.getStatus() == User.STATUS_OFFLINE) return -1;
    		}
   			return (int) (o1.getUserId() - o2.getUserId());
    	}

    }

 	public void clear() {
		elements = new ArrayList<User>();
	}
}